package com.example.arithmeticleetcode.leetcode.September;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-09-29 09:28
 **/
public class Demo23 {

    public static void main(String[] args) {
        int[] stones = {2,7,4,1,8,1};
        System.out.println(lastStoneWeight(stones));
        int[] stones1 = {1, 1};
        int[] stones2 = {7,6,7,6,9};
        System.out.println(lastStoneWeight(stones1));
        System.out.println(lastStoneWeight(stones2));
    }

    public static int lastStoneWeight(int[] stones) {
        if (stones.length == 0) {
            return 0;
        }
        Arrays.sort(stones);
        List<Integer> list = new ArrayList<>();
        for (int i = 0, len = stones.length; i < len; i++) {
            list.add(stones[i]);
        }
        int end = list.size() - 1;
        int beforeEnd = list.size() - 2;
        while (list.size() > 1) {
            int temp = Math.abs(list.get(end) - list.get(beforeEnd));
            list.remove(end);
            list.remove(beforeEnd);
            if (temp > 0) {
                list.add(temp);
            }
            Collections.sort(list);
            end = list.size() - 1;
            beforeEnd = list.size() - 2;
        }
        System.out.println(list);
        return list.size() == 0 ? 0 : list.get(0);
    }
}
